401.継承(extends)の単一キャラ

extendsを使って基底クラスを作り、共通処理を抽象化します。

p5.js oop
Learning OOP Object Oriented Programming

継承(extends)の登場!複数の種類のキャラを効率的に管理できます。

基底クラス (AbstractShape)

class AbstractShape {
  constructor() {
    this.pos = { x: ..., y: ... };
    this.speed = { x: ..., y: ... };
    this.acceleration = 0.1;
  }

  update() {
    this.pos.x += this.speed.x;
    // 共通の移動ロジック
  }

  display() {
    // サブクラスで実装
  }
}

派生クラス (Circle)

class Circle extends AbstractShape {
  display() {
    ellipse(this.pos.x, this.pos.y, 10, 10);
  }
}

継承のメリット

  • 共通部分(移動ロジック)は基底クラスに
  • 個別の部分(描画方法)は派生クラスに
  • コードの重複を避けられる

次は円と四角、2種類のキャラを継承で管理します。

View Source Code

let W, H, PW, PH;
const PADDING_RATIO = 0.2;
const MAX_SPEED = 10;

let obj;

class AbstractShape {
  constructor() {
    this.pos = {
      x: random(width),
      y: random(height),
    };
    this.speed = {
      x: (Math.random() - 0.5) * MAX_SPEED,
      y: (Math.random() - 0.5) * MAX_SPEED,
    };
    this.acceleration = 0.1;
  }

  update() {
    this.pos.x += this.speed.x;
    this.pos.y += this.speed.y;

    if (this.pos.x < 0 + PW) {
      this.speed.x += this.acceleration;
    } else if (this.pos.x > W - PW) {
      this.speed.x -= this.acceleration;
    }

    if (this.pos.y < 0 + PH) {
      this.speed.y += this.acceleration;
    } else if (this.pos.y > H - PH) {
      this.speed.y -= this.acceleration;
    }
  }

  display() {
    // implement in subclass
  }
}


class Circle extends AbstractShape {
  display() {
    stroke(0);
    fill(0);
    ellipse(this.pos.x, this.pos.y, 10, 10);
    text(["1:", Math.floor(this.pos.x), Math.floor(this.pos.y)], this.pos.x + 10, this.pos.y + 10);
  }
}

// main

function setup() {
  createCanvas((W = windowWidth), (H = windowHeight));
  PW = W * PADDING_RATIO;
  PH = H * PADDING_RATIO;

  obj = new Circle()
}

function draw() {
  background(255);

  obj.update();
  obj.display();
}